package com.gzo;


import com.alibaba.druid.pool.DruidDataSource;

import com.gzo.listen.InitListener;
import com.gzo.listen.ZkStrSerializer;
import org.I0Itec.zkclient.ZkClient;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.sql.DataSource;
import java.sql.SQLException;


@SpringBootApplication
public class ZookeeperApplication {
    public static void main(String[] args) {
        SpringApplication.run(ZookeeperApplication.class, args);
    }

    @Bean
    public ServletListenerRegistrationBean servletListenerRegistrationBean() {
        ServletListenerRegistrationBean servletListenerRegistrationBean = new ServletListenerRegistrationBean();
        servletListenerRegistrationBean.setListener(new InitListener());
        return servletListenerRegistrationBean;
    }

    @Bean
    public DataSource dataSource() throws SQLException {
        DruidDataSource dataSource = new DruidDataSource();
        ZkClient zkClient = new ZkClient("192.168.95.121:2181");
        zkClient.setZkSerializer(new ZkStrSerializer());
        String url = zkClient.readData("/zk-permanent");
        String name = "root";
        String pwd = "123456";

        dataSource.setUrl(url);
        dataSource.setUsername(name);
        dataSource.setPassword(pwd);
        dataSource.setDefaultReadOnly(false);
        dataSource.init();
        zkClient.close();
        return dataSource;
    }

    @Bean
    public JdbcTemplate jdbcTemplate() throws SQLException {
        return new JdbcTemplate(dataSource());
    }
}
